// pages/start/start.js
const app = getApp();
//富文本解析
const htmlParse = require('../../wxParse/wxParse.js');
const mta = require('../../../mta_sdk/mta_analysis.js');
const systemInfo=wx.getSystemInfoSync();
let resultPeopleCon='';
let resultThingCon=''
Page({

  data: {
    currentSort:0,
    info:'',
    actIndex:-1,
    questionType:1,
    showResult:false,
    resultContent:'',
    queryData:{},
    itemIdArr:[],
    canvasHidden:true,
    canvasWidth:systemInfo.windowWidth,
    canvasHeight:systemInfo.windowHeight,
    config:''
  },

  onLoad: function (opt) {
    console.log(opt);
    this.setData({
      queryData:opt,
      questionType:opt.type,
      config:wx.getStorageSync('config')
    })
    mta.Page.init();
    this.getItem(opt.test_id,opt.type)

  },

  //获取事情题
  getItem(id,type){
    app.ajax({
      url: type==1?"Game/get_people_item":"Game/get_thing_item",
      loading:true,
      data:{
        test_id:id
      }
    }).then(res => {
      this.setData({
        info:res.data
      })
    });
  },

  //获取人格下一题和结果
  getNextItem(id,result){
    app.ajax({
      url: "Game/people_result",
      loading:true,
      data:{
        item_id:id,
        user_reult:result,
        test_id:this.data.queryData.test_id
      }
    }).then(res => {
      if(!res.data){return false;}
      this.setData({
        info:res.data
      })
    });
  },
  //获取事情结果
  getThingResult(params){
    app.ajax({
      url: "Game/thing_result",
      loading:true,
      data:params
    }).then(res => {
      this.setData({
        showResult:true
      });
      resultThingCon=res.data.result;
      htmlParse.wxParse('article_content', 'html', res.data.result, this, 0) || ''
    });
  },
  //选中
  chooseItem(e){
    let dataset=e.currentTarget.dataset;
    let [nid,index]=[dataset.nid,dataset.index];
    this.setData({
      actIndex:index
    });
    let thisData=this.data;
    if(nid!=0){
      setTimeout(()=>{
        //如果是测试人格
        if(thisData.queryData.type==1){
          this.getNextItem(nid,'')
        }
        else{
          let newArr=thisData.itemIdArr;
          let sort=thisData.currentSort+1;
          newArr.push(nid);
          this.setData({
            itemIdArr:newArr,
            currentSort:sort
          });
          if(thisData.currentSort==thisData.info.question.length){

            this.getThingResult({
              test_id:thisData.queryData.test_id,
              option:thisData.itemIdArr
            });
          }
        }
        
        this.setData({
          actIndex:-1
        });
      },300)
    }
    else{
      this.setData({
        showResult:true
      });
      let lastResult=this.data.info.question.item[index].result;
      this.getNextItem(nid,lastResult)
      resultPeopleCon=lastResult;
      htmlParse.wxParse('article_content', 'html',lastResult , this, 0) || ''
    }

  },
  reloadPage(){
    this.setData({
      showResult: false,
      actIndex: -1,
      itemIdArr:[],
      currentSort:0
    });
    let q=this.data.queryData;
    this.getItem(q.test_id,q.type)
  },
  toHome(){
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },
  //生成图片
  createImg(){
    wx.showLoading({
      title: 'loading...',
    });
    let md=this.data;
    let queryEle = wx.createSelectorQuery();
    let ctx = wx.createCanvasContext("mycanvas"); 
    //获取要生成元素的大小
    queryEle.select('#result').boundingClientRect();
    queryEle.exec(res => {
      let codeImgWidth=res[0].width/3;//二维码宽高
      let ctx_w = res[0].width;//canvas大小
      let ctx_h = res[0].height+codeImgWidth+codeImgWidth/5;//增加画布高度
      console.log(ctx_h,res[0].height)
      this.setData({
        canvasHidden:false,
        canvasWidth:ctx_w,
        canvasHeight:ctx_h
      });
      ctx.width=ctx_w;
      ctx.height=ctx_h;
      //先绘制背景色,圆角
      function drawRoundedRect(ctx, x, y, width, height, r, fill, stroke) {
        ctx.save(); 
        ctx.beginPath(); 
        ctx.fillStyle="white";
        
        ctx.moveTo(x + r, y);
        ctx.arcTo(x + width, y, x + width, y + r, r); 
        ctx.arcTo(x + width, y + height, x + width - r, y + height, r); 
        ctx.arcTo(x, y + height, x, y + height - r, r); 
        ctx.arcTo(x, y, x + r, y, r);
        if (fill) { ctx.fill(); }
        if (stroke) { ctx.stroke(); }
        ctx.restore(); 
        //把多出的裁剪掉
        ctx.clip();
      }
      /*
      str:要绘制的字符串
      canvas:canvas对象
      initX:绘制字符串起始x坐标
      initY:绘制字符串起始y坐标
      lineHeight:字行高
      */
      function canvasTextAutoLine(str,ctx,initX,initY,lineHeight){
        var lineWidth = 0;
        var canvasWidth = ctx.width;
        var lastSubStrIndex= 0; 
        for(let i=0;i<str.length;i++){ 
            lineWidth+=ctx.measureText(str[i]).width; 
            if(lineWidth>canvasWidth/5.8*5){
                ctx.fillText(str.substring(lastSubStrIndex,i),initX,initY);
                initY+=lineHeight;
                lineWidth=0;
                lastSubStrIndex=i;
            } 
            if(i==str.length-1){
                ctx.fillText(str.substring(lastSubStrIndex,i+1),initX,initY);
            }
        }
      }
      drawRoundedRect(ctx, 0, 0, ctx_w, ctx_h, 8, true, false);
      //绘制标题背景
      ctx.fillStyle="#52a962";
      ctx.fillRect(0,0,ctx_w,60);
      //绘制标题
      ctx.setFontSize(20);
      ctx.setFillStyle("#fff");
      ctx.fillText(md.queryData.parentTitle, (ctx_w - ctx.measureText(md.queryData.parentTitle).width) / 2, 38);

      //绘制二级标题
      ctx.setFontSize(18);
      ctx.setFillStyle("#555");
      ctx.fillText(md.queryData.title, (ctx_w - ctx.measureText(md.queryData.title).width) / 2, 95);

      //绘制正文结果文字
      ctx.setFontSize(18);
      ctx.setFillStyle("#333");
      canvasTextAutoLine(md.queryData.type==1?resultPeopleCon:resultThingCon,ctx,15,135,30)
      //ctx.fillText(md.queryData.type==1?resultPeopleCon:resultThingCon, 20, 90);
      
      //绘制二维码
      ctx.drawImage('/images/code.png', (ctx_w - codeImgWidth) /2,res[0].height-codeImgWidth/30, codeImgWidth, codeImgWidth);
      ctx.draw(false,()=> {
          wx.hideLoading();
      })
    })
  },
  //保存图片到手机
  saveImg() {
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      success: function (e) {
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: function () {
            console.log(e.tempFilePath);
            wx.showToast({
              icon: "success",
              title: "保存成功"
            });
          },
          fail: function (t) {
            wx.showToast({
              icon: "none",
              title: "保存失败,请确保是否打开了图片权限",
              duration: 2000
            });
          },
          complete: function () {
          }
        });
      }
    });
  },
  //预览图片
  previewImage () {
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        console.log(tempFilePath);
        wx.previewImage({
          current: tempFilePath, // 当前显示图片的http链接  
          urls: [tempFilePath] // 需要预览的图片http链接列表  
        })
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  onShareAppMessage: function () {
    return {
      title:this.data.queryData.title,
      path:'/pages/index/index'
    }
  }
})